package com.laiyima.zhongjiang.linghuilv.demo.Serviceprovider;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.laiyima.zhongjiang.linghuilv.demo.R;
import com.laiyima.zhongjiang.linghuilv.demo.adapter.CallBackAdapter;
import com.laiyima.zhongjiang.linghuilv.demo.bean.CallbackBean;
import com.laiyima.zhongjiang.linghuilv.demo.util.TimeUtils;
import com.laiyima.zhongjiang.linghuilv.demo.view.ListViewPlus;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.CenterPopupView;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import me.imid.swipebacklayout.lib.app.SwipeBackActivity;

public class TerminalCallbackActivity extends SwipeBackActivity implements View.OnClickListener, ListViewPlus.ListViewPlusListener {
    private String TAG="TerminalCallbackActivity";
    private int tcCode,cbCode;
    private LinearLayout tc_back, tc_have_List, yuanquan;
    private TextView cbsn_count,callback_quanxuan_text;
    private Button callback_button;
    private ImageView callback_quanxuan;


    private ListViewPlus mListView;
    private CallbackBean mCallbackBean;
    private CallBackAdapter mCallBackAdapter;
    private List<CallbackBean> CallbackBeanList = new ArrayList<>();


    private int count, page_count, page_index;

    @Override
    public void onRefresh() {
        CallbackBeanList.clear();
        intView();
        mCallBackAdapter.notifyDataSetChanged();

        loadData(ListViewPlus.REFRESH);
        // Log.e(TAG, "onRefresh:");

    }

    @Override
    public void onLoadMore() {
        if (page_index < page_count) {
            loadData(ListViewPlus.LOAD);
        } else {
            Toast.makeText(getBaseContext().getApplicationContext(), "已全部加载", Toast.LENGTH_SHORT).show();
            onLoadComplete();
        }
    }

    private void loadData(final int what) {
        // 这里模拟从服务器获取数据
        new Thread(new Runnable() {
            @Override
            public void run() {

                Message msg = handler.obtainMessage();
                msg.what = what;
                handler.sendMessage(msg);
            }
        }).start();
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ListViewPlus.REFRESH:
                    //intView();
                    onLoadComplete();
                    // Toast.makeText(getContext().getApplicationContext(), "已刷新数据", Toast.LENGTH_SHORT).show();
                    break;
                case ListViewPlus.LOAD:
                    page_index++;
                    loadMode(page_index);
                    break;
            }

        }

    };

    private void onLoadComplete() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime(TimeUtils.getCurrentTime());
    }

    protected boolean useThemestatusBarColor = false;//是否使用特殊的标题栏背景颜色，android5.0以上可以设置状态栏背景色，如果不使用则使用透明色值

    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            //根据上面设置是否对状态栏单独设置颜色
            if (useThemestatusBarColor) {
                // getWindow().setStatusBarColor(getResources().getColor(R.color.colorTheme));
            } else {
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//android6.0以后可以对状态栏文字颜色和图标进行修改
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_terminal_callback);
        tc_back = (LinearLayout) findViewById(R.id.tc_back);
        tc_back.setOnClickListener(this);
        cbsn_count = (TextView) findViewById(R.id.cbsn_count);
        callback_button = (Button) findViewById(R.id.callback_button);
        callback_button.setOnClickListener(this);
        tc_have_List = (LinearLayout) findViewById(R.id.tc_have_List);

        mListView = (ListViewPlus) findViewById(R.id.callback_sn_list);
        mListView.setRefreshEnable(true);
        mListView.setLoadEnable(true);
        mListView.setAutoLoadEnable(true);
        mListView.setRefreshTime(TimeUtils.getCurrentTime());
        mListView.setListViewPlusListener(this);
        callback_quanxuan = (ImageView) findViewById(R.id.callback_quanxuan);
        callback_quanxuan.setOnClickListener(this);
        yuanquan = (LinearLayout) findViewById(R.id.yuanquan);
        yuanquan.setOnClickListener(this);
        callback_quanxuan_text= (TextView) findViewById(R.id.callback_quanxuan_text);
        callback_quanxuan_text.setOnClickListener(this);

        setListener();


        intView();
        setStatusBar();
    }

    private String select_sn = "";
    private int selectCode = 0;

    private void setListener() {
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ListViewPlus listView = (ListViewPlus) parent;
                CallbackBean mCallbackBean = (CallbackBean) listView.getItemAtPosition(position);
                String sn = mCallbackBean.getSn();
                if (mCallbackBean.isChecked()) {
                    select_sn = select_sn.replace(sn, "");
                    selectCode = selectCode - 1;
                    mCallbackBean.setChecked(false);
                } else {
                    selectCode = selectCode + 1;
                    select_sn = "," + sn + select_sn;
                    mCallbackBean.setChecked(true);
                }
                cbsn_count.setText( selectCode+ "/"+count);
                mCallBackAdapter.notifyDataSetChanged();
            }
        });

    }


    private void intView() {
        SharedPreferences sharedPreferences = getBaseContext().getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/callback");
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("page_size", 10);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    tcCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    if (!TextUtils.isEmpty(data)) {
                        JSONObject jsonObjec = new JSONObject(data);
                        count = jsonObjec.optInt("count", 0);
                        cbsn_count.setText( 0+ "/"+count);
                        page_count = jsonObjec.optInt("page_count", 0);
                        page_index = jsonObjec.optInt("page_index", 0);
                    }
                    JSONObject jData = new JSONObject(data);
                    JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String merName = value.getString("merName");
                        String sn = value.getString("sn");
                        String start = value.getString("start");
                        mCallbackBean = new CallbackBean(merName, sn, start);
                        CallbackBeanList.add(mCallbackBean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (tcCode == 200) {
                    mCallBackAdapter = new CallBackAdapter(getBaseContext().getApplicationContext(), CallbackBeanList);
                    mCallBackAdapter.notifyDataSetChanged();
                    mListView.setAdapter(mCallBackAdapter);
                }
                if (tcCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                if (CallbackBeanList.size() == 0) {
                    tc_have_List.setVisibility(View.VISIBLE);
                } else {
                    tc_have_List.setVisibility(View.GONE);
                }
            }
        });

    }


    private void loadMode(int page_index) {
        SharedPreferences sharedPreferences = getBaseContext().getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/callback");
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("page_index", page_index);
        params.addBodyParameter("page_size", 10);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    tcCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    JSONObject jData = new JSONObject(data);
                    JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String merName = value.getString("merName");
                        String sn = value.getString("sn");
                        String start = value.getString("start");
                        mCallbackBean = new CallbackBean(merName, sn, start);
                        CallbackBeanList.add(mCallbackBean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (tcCode == 200) {
                    mCallBackAdapter.notifyDataSetChanged();
                }
                if (tcCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                onLoadComplete();
            }
        });

    }



    private void dialog_show() {
        TerminalCallbackActivity.CustomPopup customPopup = new TerminalCallbackActivity.CustomPopup(this);
        new XPopup.Builder(this)
                .asCustom(customPopup)
                .show();
    }
    public  class CustomPopup extends CenterPopupView {
        private TextView mytextView,banlance_resout;
        public CustomPopup(@NonNull Context context) {
            super(context);
        }
        @Override
        protected int getImplLayoutId() {
            return R.layout.banlance_custom_popup;
        }
        @Override
        protected void onCreate() {
            super.onCreate();
            banlance_resout=findViewById(R.id.banlance_resout);
            banlance_resout.setText("请确认回调");
            mytextView=findViewById(R.id.balance_tishi);
            mytextView.setText("");
            findViewById(R.id.banlance_dialog_button).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    callback();
                    dismiss();
                }
            });
        }
        protected void onShow() {
            super.onShow();
        }
    }



    private int cb = 1;
    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.tc_back:
                finish();
                break;
            case R.id.callback_button:
                if (selectCode == 0) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "请选要回拨的号", Toast.LENGTH_SHORT).show();
                } else {
                    dialog_show();
                }

                break;
            case R.id.callback_quanxuan_text:
                if (cb == 1) {
                     cb = 2;
                    for (int i = 0; i < CallbackBeanList.size(); i++) {
                        select_sn = "," + CallbackBeanList.get(i).getSn() + select_sn;
                        selectCode = CallbackBeanList.size();
                        CallbackBeanList.get(i).setChecked(true);
                        cbsn_count.setText( CallbackBeanList.size()+ "/"+count);
                    }
                } else {
                    cbsn_count.setText( 0+ "/"+count);
                     cb = 1;
                    for (int i = 0; i < CallbackBeanList.size(); i++) {
                        selectCode = 0;
                        CallbackBeanList.get(i).setChecked(false);
                    }
                }
                mCallBackAdapter.notifyDataSetChanged();
               break;

        }

    }

    private void callback() {
        if (selectCode == 0) {
            Toast.makeText(getBaseContext().getApplicationContext(), "请选要回拨的号", Toast.LENGTH_SHORT).show();
        } else {
            SharedPreferences sharedPreferences = getBaseContext().getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
            String userID = sharedPreferences.getString("userID", "");
            RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/callback_upload");
            params.addBodyParameter("uid", userID);
            params.addBodyParameter("sn", select_sn);
            Log.e(TAG, "userID:"+userID+"    select_sn"+select_sn);
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    try {
                    JSONObject jsonObject = new JSONObject(result);
                    cbCode = jsonObject.optInt("code", 0);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (cbCode == 200) {
                        Toast.makeText(getBaseContext().getApplicationContext(), "回拨成功", Toast.LENGTH_SHORT).show();
                        onRefresh();
                        mCallBackAdapter.notifyDataSetChanged();
                        select_sn = "";
                        selectCode = 0;
                        callback_quanxuan.setImageResource(R.drawable.cb_fase);
                        cb = 1;
                    }
                    if (cbCode == 404) {
                        Toast.makeText(getBaseContext().getApplicationContext(), "划拨失败", Toast.LENGTH_SHORT).show();
                    }
                    if (cbCode == 500) {
                        Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {
                }

                @Override
                public void onFinished() {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Message msg = handler1.obtainMessage();
                            msg.what = 20;
                            handler1.sendMessage(msg);
                        }
                    }).start();

                }
            });
        }
    }
    Handler handler1 = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 20:
                    selectCode = 0;
                    CallbackBeanList.clear();
                    intView();
            }
        }
    };
}

